package cn.fl.capital.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapClaimInfoQC;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.condition.CapPayeeInfoQueryCondition;
import cn.fl.capital.constant.CapClaimInfoConstant;
import cn.fl.capital.constant.CapPayInfoConstant;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapClaimInfoDTO;
import cn.fl.capital.dto.CapPayeeInfoDTO;
import cn.fl.capital.service.ICapClaimInfoApiService;
import cn.fl.capital.service.ICapClaimInfoService;
import cn.fl.capital.service.ICapPayeeInfoApiService;
import cn.fl.capital.transform.CapClaimInfoFlowSHVOTransform;
import cn.fl.capital.transform.CapClaimInfoVOTransform;
import cn.fl.capital.transform.CapPayeeInfoVOTransform;
import cn.fl.capital.vo.CapClaimInfoFlowSHVO;
import cn.fl.capital.vo.CapClaimInfoVO;
import cn.fl.capital.vo.CapPayeeInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.spl.api.ISplRenewProtocolRecApiService;
import fl.spl.facade.spl.condition.SplRenewProtocolRecQC;
import fl.spl.facade.spl.dto.SplRenewProtocolRecDTO;


/**
 * @Description: 超时理赔记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class CapClaimInfoServiceImpl implements ICapClaimInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(CapClaimInfoServiceImpl.class);
	
	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	//@Autowired
	//private I自定义ApiService 自定义ApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ICapClaimInfoApiService capClaimInfoApiService;
    @Autowired
    private ISplRenewProtocolRecApiService splRenewProtocolRecApiService;

    /**
     * 组织架构API
     */
    @Autowired
    private ISysOrgApiService sysOrgApiService;
    @Autowired
    private ICapPayeeInfoApiService capPayeeInfoApiService;

	@Override
	public CapClaimInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		CapClaimInfoDTO dto = this.capClaimInfoApiService.selectCapClaimInfoById(id);
		return CapClaimInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapClaimInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不存在!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		};
		return this.capClaimInfoApiService.addCapClaimInfo(CapClaimInfoVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return this.capClaimInfoApiService.removeCapClaimInfoById(id);
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return this.capClaimInfoApiService.removeCapClaimInfoByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

	@Override
	public boolean modify(CapClaimInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		};
		return this.capClaimInfoApiService.modifyCapClaimInfo(CapClaimInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		return this.capClaimInfoApiService.searchCapClaimInfoListPage(page);
	}

	@Override
	public Pager searchCapPayInfoListPage(Pager page) throws BaseException {
		CapClaimInfoQC condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new CapPayInfoQueryCondition());
        }
        condition = (CapClaimInfoQC) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        condition.setPayTypCd(CapPayInfoConstant.CODE_PAY_TYP_CD_5);//准时放款
        page = this.capClaimInfoApiService.searchCapPayInfoListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<CapClaimInfoVO> voList = CapClaimInfoVOTransform.toVOList((List<CapClaimInfoDTO>) page.getResultList());
            this.setCapClaimInfoData(voList);
            this.setCapPayInfoDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	/**
	 * 设置超时赔付等信息
	 * @param voList
	 */
	private void setCapClaimInfoData(List<CapClaimInfoVO> voList){
		if (CollectionUtils.isEmpty(voList)) return;
		List<Long> idList=new ArrayList<Long>(voList.size());
		List<Long> splIdList=new ArrayList<Long>(voList.size());
		for (CapClaimInfoVO vo : voList) {
			idList.add(vo.getId());
			splIdList.add(vo.getSplId());
		}
		//供应商协议有效状态
		Map<Long, Integer> splInfoMap = new HashMap<Long, Integer>();
		SplRenewProtocolRecQC qc = new SplRenewProtocolRecQC();
		qc.setSplIdList(splIdList);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		qc.setChlCd(SplSystemConstant.FL_WEB_CHL_CD);//渠道代码
		qc.setIsNew(1);
		qc.setIsDel(0);
		List<SplRenewProtocolRecDTO> splRenewProtocolRecDTOs= this.splRenewProtocolRecApiService.searchSplRePtlRecDTOList(qc);
		if(CollectionUtils.isNotEmpty(splRenewProtocolRecDTOs)){
			for(SplRenewProtocolRecDTO dto:splRenewProtocolRecDTOs){
				splInfoMap.put(dto.getSplId(), dto.getIsValid());
			}
		}
		
		//实际赔付金额及时间
		CapPayeeInfoQueryCondition payeeQc = new CapPayeeInfoQueryCondition();
        payeeQc.setPayIds(idList);
        payeeQc.setPurpCd(CapitalConstant.CODE_SPL_BK_PURP_CD_10);//超时理赔账号
        List<CapPayeeInfoDTO> capPayeeInfoVOList = this.capPayeeInfoApiService.searchCapPayeeInfoList(payeeQc);
        Map<Long, CapPayeeInfoDTO> payeeMap = null;
        if (CollectionUtils.isNotEmpty(capPayeeInfoVOList)) {
            payeeMap = new HashMap<>(capPayeeInfoVOList.size());
            for (CapPayeeInfoDTO payeeInfoDTO : capPayeeInfoVOList) {
                if (null != payeeInfoDTO.getActPayTm()) {
                    payeeMap.put(payeeInfoDTO.getPayId(), payeeInfoDTO);
                }
            }
        }
		
		for(CapClaimInfoVO vo:voList){
			if(splInfoMap!=null && splInfoMap.containsKey(vo.getSplId())){
				vo.setIsValid(splInfoMap.get(vo.getSplId()));
			}
			if(payeeMap!=null && payeeMap.containsKey(vo.getId())){
				CapPayeeInfoDTO payeeInfoDTO = payeeMap.get(vo.getId());
				vo.setPayClaimAmt(payeeInfoDTO.getActPayAmt());
				vo.setClaimTm(payeeInfoDTO.getActPayTm());
			}
			vo.setTakeMsStr(this.getFormatTimeStampToStr(vo.getTakeMs(), 0));
		}
	}
	
	 /**
     * 添加数据字典名称
     *
     * @param voList
     */
    public void setCapPayInfoDictData(List<CapClaimInfoVO> voList) {
        if (CollectionUtils.isEmpty(voList)) return;
        //放款状态
        Map<String, String> payStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapPayInfoConstant.CODE_PAY_STS_CD);
        //赔付状态
        Map<String, String> claStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapClaimInfoConstant.CODE_CLA_STS_CD);
        //供应商有效类型
        Map<String, String> splIsValidMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapClaimInfoConstant.CODE_SPL_IS_VALID);
        
        //事业部组织架构
        List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
        Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysOrgDTO sysOrgDTO : list) {
                buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
            }
        }
        SysOrgDTO sysOrgDTO = null;
        String orgCd = null;
        for (CapClaimInfoVO vo : voList) {
            if (payStsCdMap != null && payStsCdMap.containsKey(vo.getPayStsCd())) {
                vo.setPayStsCdNm(payStsCdMap.get(vo.getPayStsCd()));
            }
            if (buOrgCdMap.containsKey(vo.getBuOrgCd())) {
                vo.setBuOrgCdNm(buOrgCdMap.get(vo.getBuOrgCd()).getOrgNm());
            }
            if (claStsCdMap != null && claStsCdMap.containsKey(vo.getClaStsCd())) {
                vo.setClaStsCdNm(claStsCdMap.get(vo.getClaStsCd()));
            }
            if(splIsValidMap!=null && splIsValidMap.containsKey(vo.getIsValid())){
            	vo.setSplIsValidNm(splIsValidMap.get(vo.getIsValid()));
            }
            if (buOrgCdMap.containsKey(vo.getCstMgrOrgCd())) {
                sysOrgDTO = buOrgCdMap.get(vo.getCstMgrOrgCd());
                vo.setCstMgrOrgCdNm(sysOrgDTO.getOrgNm());
                orgCd = sysOrgDTO.getOrgCd();
                while(orgCd.length()>8){
                    if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
                        vo.setCyOrgCdNm(sysOrgDTO.getOrgNm());
                    }else if("3".equals(sysOrgDTO.getOrgTypCd())){
                        vo.setPrOrgCdNm(sysOrgDTO.getOrgNm());
                        break;
                    }
                    orgCd = orgCd.substring(0,orgCd.length()-4);
                    if(buOrgCdMap.containsKey(orgCd)){
                        sysOrgDTO = buOrgCdMap.get(orgCd);
                    }else{
                        break;
                    }
                }
            }
        }
    }
    /**
	 * 理赔状态
	 * @return
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getClaStsCdList() throws BaseException {
		return this.sysDictionaryApiService.getKvList(CapClaimInfoConstant.CODE_CLA_STS_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
	}
    @Override
    public List<CapClaimInfoFlowSHVO> searchCapCaimFlowList(Long splId) throws BaseException {

//        return CapClaimInfoFlowSHVOTransform.toVOList(this.capClaimInfoApiService.searchCapClaimFlowList(splId,CurrentThreadContext.getCurrentSysCd()));
    	return null;
    }
	/**
	 * 查询理赔记录表及放款表信息
	 * @param claimId
	 * @return
	 * @throws BaseException
	 */
	@Override
	public CapClaimInfoVO selectCapClaimInfoAndCapPayInfoById(Long claimId)
			throws BaseException {
		CapClaimInfoVO vo = CapClaimInfoVOTransform.toVO(this.capClaimInfoApiService.selectCapClaimInfoAndCapPayInfoById(claimId,CurrentThreadContext.getCurrentSysCd()));
		//查询实际付款时间
        CapPayeeInfoQueryCondition payeeQc = new CapPayeeInfoQueryCondition();
        payeeQc.setPayId(claimId);
        payeeQc.setPurpCd(CapitalConstant.CODE_SPL_BK_PURP_CD_10);//理赔账号
        List<CapPayeeInfoDTO> capPayeeInfoList = this.capPayeeInfoApiService.searchCapPayeeInfoList(payeeQc);
        if (CollectionUtils.isNotEmpty(capPayeeInfoList)) {
            vo.setPayeeList(CapPayeeInfoVOTransform.toVOList(capPayeeInfoList));
        }else{//没有理赔帐号查询放款帐号
        	payeeQc.setPayId(vo.getPayId());
        	payeeQc.setPurpCd(CapitalConstant.CODE_SPL_BK_PURP_CD_1);
        	List<CapPayeeInfoDTO> capPayeeInfoListFK = this.capPayeeInfoApiService.searchCapPayeeInfoList(payeeQc);
        	if (CollectionUtils.isNotEmpty(capPayeeInfoListFK)) {
        		for(CapPayeeInfoDTO dto:capPayeeInfoListFK){
        			dto.setActPayAmt(null);
        			dto.setActPayTm(null);
        		}
        		vo.setPayeeList(CapPayeeInfoVOTransform.toVOList(capPayeeInfoListFK));
            }
        }
		if(CollectionUtils.isNotEmpty(vo.getPayeeList())){
			for(CapPayeeInfoVO capPayeeInfoVO:vo.getPayeeList()){
				capPayeeInfoVO.setActPayTms(capPayeeInfoVO.getActPayTm()!=null?DateUtils.formatDateToString(capPayeeInfoVO.getActPayTm(), DateUtils.YYYY_MM_DD):"");
			}
		}
		
		//放款状态
        Map<String, String> payStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapPayInfoConstant.CODE_PAY_STS_CD);
        //赔付类型
        Map<String, String> claStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapClaimInfoConstant.CODE_CLA_STS_CD);
        //事业部组织架构
        List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
        Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysOrgDTO sysOrgDTO : list) {
                buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
            }
        }
        if (payStsCdMap != null && payStsCdMap.containsKey(vo.getPayStsCd())) {
            vo.setPayStsCdNm(payStsCdMap.get(vo.getPayStsCd()));
        }
        if (buOrgCdMap.containsKey(vo.getBuOrgCd())) {
            vo.setBuOrgCdNm(buOrgCdMap.get(vo.getBuOrgCd()).getOrgNm());
        }
        if (claStsCdMap != null && claStsCdMap.containsKey(vo.getClaStsCd())) {
            vo.setClaStsCdNm(claStsCdMap.get(vo.getClaStsCd()));
        }
        vo.setTakeMsStr(this.getFormatTimeStampToStr(vo.getTakeMs(), 0));
		return vo;
	}

	@Override
	public List<KeyValueVO> getPayeeTypCdList() throws BaseException {
		return this.sysDictionaryApiService.getKvList(CapClaimInfoConstant.CODE_PAYEE_TYP_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
	}

	@Override
	public List<KeyValueVO> getBkAccTypCdList() throws BaseException {
		return this.sysDictionaryApiService.getKvList(CapClaimInfoConstant.CODE_BK_ACC_TYP_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
	}

	@Override
	public List<KeyValueVO> getPayWayCdList() throws BaseException {
		return this.sysDictionaryApiService.getKvList(CapClaimInfoConstant.CODE_PAY_WAY_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
	}
    @Override
    public DataResultDTO addFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException{
        if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
            BaseLogUtils.info(logger, "addFlowStart", "用户ID和业务数据主键必须要存在!",CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID和业务数据主键必须要存在!");
        }
        return this.capClaimInfoApiService.addFlowStart(flowStartParamsDTO);
    }

	@Override
	public boolean modifyCapClaimInfoByFlow(CapClaimInfoVO entity)
			throws BaseException {
		return this.capClaimInfoApiService.modifyCapClaimInfoByFlow(CapClaimInfoVOTransform.toDTO(entity));
	}

	/**
	 * 毫秒转成年月日时分秒
	 * @param diff 时间毫秒数
	 * @param type 0 ：年月日时分秒
	 * @return
	 */
	private String getFormatTimeStampToStr(Long diff, int type) {
        // 按照传入的格式生成一个simpledateformate对象
		if(StringUtils.isEmpty(diff)){
			return "-";
		}
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异
        try {
            if(diff < 0){
            	return "-";
            }
            day = diff / nd;// 计算差多少天
            hour = diff % nd / nh + day * 24;// 计算差多少小时
            min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
            sec = diff % nd % nh % nm / ns;// 计算差多少秒
            if (type == 0) {
            	if(day == 0 && (hour - day * 24) == 0 && (min - day * 24 * 60) == 0){
            		return sec + "秒";
            	}else if(day == 0 && (hour - day * 24) == 0){
            		return (min - day * 24 * 60) + "分" + sec + "秒";
            	}else if(day == 0){
            		return (hour - day * 24) + "时" + (min - day * 24 * 60) + "分" + sec + "秒";
            	}
                return day + "天" + (hour - day * 24) + "时" + (min - day * 24 * 60) + "分" + sec + "秒";
            } else {
                return "";
            }

        } catch (Exception e) {
            return "";
        }
	}
    @Override
    public List<CapClaimInfoFlowSHVO> searchCapClaimFlowList(Long capClaimId) throws BaseException {
        return CapClaimInfoFlowSHVOTransform.toVOList(this.capClaimInfoApiService.searchCapClaimFlowList(capClaimId,CurrentThreadContext.getCurrentSysCd()));
    }
}
